package namespace

import (
	"context"
	"gitee/yinlai/kms-backend/config"
	"gitee/yinlai/kms-backend/controllers"
	"gitee/yinlai/kms-backend/utils/logs"
	"github.com/gin-gonic/gin"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"net/http"
)

func Delete(r *gin.Context) {
	logs.Debug(nil, "删除Namespace")

	clientset, basicInfo, err := controllers.BasicInit(r, nil)
	returnData := config.ReturnData{}
	if err != nil {
		returnData.Message = err.Error()
		returnData.Status = 400
		r.JSON(http.StatusOK, returnData)
		return
	}

	// 如果是k8s内部namespace禁止删除
	if basicInfo.Name == "kube-system" {
		returnData.Message = "禁止删除kube-system"
		returnData.Status = 400
		r.JSON(http.StatusOK, returnData)
		return
	}

	err = clientset.CoreV1().Namespaces().Delete(context.TODO(), basicInfo.Name, metav1.DeleteOptions{})
	if err != nil {
		logs.Error(map[string]interface{}{"id": basicInfo.ClusterId, "msg": err.Error()}, "删除Namespace失败")
		msg := "删除Namespace失败：" + err.Error()
		returnData.Status = 400
		returnData.Message = msg
	} else {
		returnData.Message = "删除成功"
		returnData.Status = 200
	}
	r.JSON(http.StatusOK, returnData)
}
